package org.pay.manage.order.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.pay.manage.common.service.RpcCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.pay.core.common.constant.Constant;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.common.domain.PayPageRes;
import org.pay.core.common.domain.PayResponse;
import org.pay.core.entity.MchNotify;
import org.pay.manage.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/mch_notify")
@PreAuthorize("hasRole('"+ MchConstant.MGR_ROLE_NORMAL+"')")
public class MchNotifyController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 查询单条商户通知记录
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String orderId = getStringRequired(param, "orderId");
        MchNotify mchNotify = rpcCommonService.rpcMchNotifyService.findByOrderId(orderId);
        return ResponseEntity.ok(PayResponse.buildSuccess(mchNotify));
    }

    /**
     * 商户通知记录列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer page = getInteger(param, "page");
        Integer limit = getInteger(param, "limit");
        MchNotify mchNotify = getObject(param, MchNotify.class);
        int count = rpcCommonService.rpcMchNotifyService.count(mchNotify);
        if(count == 0) ResponseEntity.ok(PayPageRes.buildSuccess());
        List<MchNotify> mchNotifyList = rpcCommonService.rpcMchNotifyService.select(
                (getPageIndex(page) -1) * getPageSize(limit), getPageSize(limit), mchNotify);
        return ResponseEntity.ok(PayPageRes.buildSuccess(mchNotifyList, count));
    }

    /**
     * 重发通知(待实现)
     * @return
     */
    @RequestMapping("/resend")
    @ResponseBody
    public ResponseEntity<?> resend(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String orderId = getStringRequired(param, "orderId");
        MchNotify mchNotify = rpcCommonService.rpcMchNotifyService.findByOrderId(orderId);
        return ResponseEntity.ok(PayResponse.buildSuccess(mchNotify));
    }

}